<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <BasicTable
          @register="registerTable"
          :columns="columns"
          :dataSource="tableData"
          :canResize="false"
          :showIndexColumn="false"
          :striped="true"
          :bordered="true"
          :pagination="false"
          :actionColumn="
            hasPermission([
              '7-2-update',
              '7-2-lookElement',
              '7-2-lookProduct',
              '7-2-copy',
              '7-2-del',
            ])
              ? actionColumn
              : undefined
          "
          rowKey="RecipeKey"
          :rowSelection="{
            type: 'checkbox',
            checkStrictly: true,
            onChange(selectedRowKeys) {
              onChangeByTable(selectedRowKeys);
            },
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    label: '编辑',
                    ifShow: hasPermission('7-2-update'),
                    onClick: (e) => {
                      e.stopPropagation();
                      handleEdit(record);
                    },
                  },
                  {
                    label: '成分',
                    ifShow: hasPermission('7-2-lookElement'),
                    onClick: (e) => {
                      e.stopPropagation();
                      handleElement(record);
                    },
                  },
                  {
                    label: '产品',
                    ifShow: hasPermission('7-2-lookProduct'),
                    onClick: (e) => {
                      e.stopPropagation();
                      handleProduct(record);
                    },
                  },
                  {
                    label: '复制',
                    ifShow: hasPermission('7-2-copy'),
                    onClick: (e) => {
                      e.stopPropagation();
                      handleCopy(record);
                    },
                  },
                  {
                    label: '删除',
                    ifShow: hasPermission('7-2-del'),
                    onClick: (e) => {
                      e.stopPropagation();
                      handleDelete(record);
                    },
                  },
                ]"
              />
            </template>
          </template>
          <template #toolbar>
            <a-input-search
              v-model:value="searchValue"
              placeholder="请输入"
              style="width: 300px"
              :allowClear="true"
              @search="onSearch"
            />
            <a-button type="primary" @click="handleAdd" v-if="hasPermission('7-2-add')">
              新增
            </a-button>
            <a-button
              v-if="isShowBatchDel && hasPermission('7-2-batchDel')"
              type="primary"
              @click="handleBatchDel"
              :loading="loadingByBtn"
            >
              批量删除
            </a-button>
            <a-button type="primary" @click="handleSave" v-if="hasPermission('7-2-save')">
              保存到配置文件
            </a-button>
          </template>
        </BasicTable>
        <div class="flex py-2 items-center justify-end pagination-box">
          <a-pagination
            :show-total="(total) => `共 ${total} 条数据`"
            showSizeChanger
            size="small"
            :current="paginationInfo.data.current"
            :pageSize="paginationInfo.data.pageSize"
            :total="paginationInfo.data.total"
            @change="handlePageChange"
          />
        </div>
      </div>
    </div>
    <!-- 新增或编辑的弹窗 -->
    <modelByDetail
      :info="detailForm"
      @register="registerByDetail"
      @submit-success="handelUpateTable"
    />
    <!-- 成分列表抽屉 -->
    <drawerByElements @register="registerByElements" :info="detailForm" />
    <!-- 产品列表抽屉 -->
    <drawerByProducts @register="registeByProducts" :info="detailForm" />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { usePermission } from '/@/hooks/web/usePermission';
  import { ref, onMounted, reactive, h, onDeactivated } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';

  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Pagination } from 'ant-design-vue';
  import { useDrawer } from '/@/components/Drawer';

  import modelByDetail from '/@/views/project/formula/components/modelByDetail.vue';
  import drawerByElements from '/@/views/project/formula/components/drawerByElements.vue';
  import drawerByProducts from '/@/views/project/formula/components/drawerByProduct.vue';

  import {
    saveconfig,
    getrecipeitems,
    copyrecipe,
    delrecipe,
    batchdelrecipe,
  } from '/@/api/formula/index';

  const APagination = Pagination;
  const { createConfirm, createMessage } = useMessage();
  const [registerTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable();
  const { t } = useI18n();
  const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] =
    useModal();
  const [
    registerByElements,
    { openDrawer: openDrawerByElements, closeDrawer: closeDrawerByElements },
  ] = useDrawer();
  const [
    registeByProducts,
    { openDrawer: openDrawerByProducts, closeDrawer: closeDrawerByProducts },
  ] = useDrawer();
  const { hasPermission } = usePermission();
  // 分页信息
  let paginationInfo = reactive({
    data: {
      pageSize: 50,
      total: 0,
      current: 1,
    },
  });
  let detailForm = reactive({
    type: 'add',
    data: {},
  });
  let searchValue = ref('');
  let isShowBatchDel = ref(false);
  let loadingByBtn = ref(false);
  let tableData = reactive([]);
  let isSearch = false;
  let loading = ref(false);
  // 表格表头

  let columns: BasicColumn[] = [
    {
      title: '配方名称',
      dataIndex: 'Name',
    },
    {
      title: '设备',
      dataIndex: 'DevicesFullName',
    },
    {
      title: '工序',
      dataIndex: 'Process',
    },
    {
      title: '描述',
      dataIndex: 'Description',
    },
  ];
  // 操作栏
  let actionColumn = {
    width: 250,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };
  // 新增或编辑成功事件
  function handelUpateTable() {
    detailForm.type = 'add';
    detailForm.data = {};
    closeModalByDetail();
    getTableData();
  }
  // 搜索方法
  function onSearch() {
    isSearch = ['', null, undefined].indexOf(searchValue.value) === -1;
    paginationInfo.data.current = 1;
    getTableData();
  }
  // 表格选中事件
  function onChangeByTable(selectedRowKeys) {
    isShowBatchDel.value = selectedRowKeys.length > 0;
  }
  // 编辑
  function handleEdit(params) {
    detailForm.type = 'update';
    detailForm.data = params;
    openModalByDetail();
  }
  // 成分
  function handleElement(params) {
    detailForm.type = 'elements';
    detailForm.data = params;
    openDrawerByElements();
  }
  // 产品
  function handleProduct(params) {
    detailForm.type = 'products';
    detailForm.data = params;
    openDrawerByProducts();
  }
  // 复制
  function handleCopy(params) {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认复制该配方(${params.Name})`),
      onOk: async () => {
        try {
          await copyrecipe([params.RecipeKey]);
          getTableData();
          createMessage.success(t('layout.setting.operatingTitle'));
        } catch (error) {}
      },
    });
  }

  //删除
  function handleDelete(params) {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除该配方(${params.Name})`),
      onOk: async () => {
        try {
          await delrecipe([params.RecipeKey]);
          getTableData();
          createMessage.success(t('layout.setting.operatingTitle'));
        } catch (error) {}
      },
    });
  }
  // 批量删除
  function handleBatchDel() {
    let keys = getSelectRowKeys();
    let targetNames = tableData
      .filter((item) => keys.indexOf(item.RecipeKey) >= 0)
      .map((item) => item.Name)
      .join('、');
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除选中的配方(${targetNames})`),
      onOk: async () => {
        try {
          await batchdelrecipe([keys]);
          getTableData();
          createMessage.success(t('layout.setting.operatingTitle'));
        } catch (error) {}
      },
    });
  }
  // 分页事件
  function handlePageChange(page, pageSize) {
    paginationInfo.data.current = page;
    paginationInfo.data.pageSize = pageSize;
    getTableData();
  }
  // 保存
  function handleSave() {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `此操作将会把页面内容保存到配置文件，是否确认该操作？`),
      onOk: async () => {
        try {
          await saveconfig();
          createMessage.success(t('layout.setting.operatingTitle'));
        } catch (error) {}
      },
    });
  }
  // 新增
  function handleAdd() {
    detailForm.type = 'add';
    detailForm.data = {};
    openModalByDetail();
  }
  // 获取设备集合
  async function getTableData() {
    clearSelectedRowKeys();
    try {
      loading.value = true;
      let res = await getrecipeitems([
        {
          PageNO: paginationInfo.data.current,
          SearchValue: isSearch ? searchValue.value : '',
          PageSize: paginationInfo.data.pageSize,
        },
      ]);
      paginationInfo.data.total = res.TotalRows;
      tableData = res.Rows;
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  onMounted(async () => {
    getTableData();
  });
  onDeactivated(() => {
    closeDrawerByElements();
    closeDrawerByProducts();
  });
</script>
<script lang="ts">
  export default {
    name: 'FormulaIndexPage',
  };
</script>
<style scoped lang="less">
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }

    .tag::after {
      content: '';
      display: block;
      width: 100%;
      height: 45px;
    }
  }
</style>
